******SET YOUR DIRECTORY to ...\replication




***Racial segregation
import delimited "rawdata\LR_segregation\nhgis0011_ts_nominal_place.csv", clear 

 g pop2000 = b18aa2000 + b18ab2000 + b18ac2000 + b18ad2000 + b18ae2000
 g pop2010 = b18aa2010 + b18ab2010 + b18ac2010 + b18ad2010 + b18ae2010
 rename b18ab2000 black2000
 rename b18ab2010 black2010
 rename gjoin200 fip_plc
 
 drop if fip_plc == ""
 keep  fip_plc statefp pop* black* name2000
 
 reshape long pop black, i(fip_plc statefp name2000) j(year)
 
 replace fip_plc = subinstr(fip_plc, "G", "",.) 
 destring fip_plc, replace
 
 g state = statefp * 1000000 
 g pl_id = fip_plc - state
 
replace state = state/10
 
 g fipsplace_00 = state + pl_id
 
 g lr_cpctblk = (black / pop) *100
 
 keep year fipsplace_00 lr_cpctblk
 
save "rawdata\LR_segregation\LR_shblack.dta", replace


***Income segregation
import delimited "rawdata\LR_segregation\nhgis0012_ts_nominal_place.csv", clear 

 rename b79aa1980 med1980
 rename b79aa1990 med1990
 rename b79aa2000 med2000
 rename b79aa125 med2010
 rename gjoin200 fip_plc
 
 drop if fip_plc == ""
 keep  fip_plc statefp med* name2000
 
 reshape long med, i(fip_plc statefp name2000) j(year)
 
 replace fip_plc = subinstr(fip_plc, "G", "",.) 
 destring fip_plc, replace
 
 g state = statefp * 1000000 
 g pl_id = fip_plc - state
 
replace state = state/10
 
 g fipsplace_00 = state + pl_id
 
 keep year fipsplace_00 med name2000
 
save "rawdata\LR_segregation\temp.dta", replace



use "intermediatedata\bridge_final.dta", clear

keep FSTATE FPLACE PLACENM FMSA city_center POP

g state = FSTATE * 100000
g fipsplace_00 = state + FPLACE

duplicates drop fipsplace_00, force

save "rawdata\LR_segregation\list_CC_NCC.dta", replace




use "rawdata\LR_segregation\temp.dta", clear

merge n:1  fipsplace_00 using "rawdata\LR_segregation\list_CC_NCC.dta", keepusing(city_center FMSA POP)

drop if _merge!=3

drop if FMSA==.

g wXinc = med * POP
bysort FMSA year: egen NUM = total(wXinc)
bysort FMSA year: egen DEN = total(POP)

g _temp = NUM / DEN
bysort FMSA year:  egen lr_income = min(_temp)
drop wXinc _temp NUM DEN

drop if city_center!=1
rename med lr_cincome

drop _merge
save "rawdata\LR_segregation\LR_income.dta", replace